package cc.rboot.feign.transcoder;

import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import java.io.IOException;
import java.lang.reflect.Type;

public class FeignDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.status() == 404) {
            return Util.emptyValueOf(type);
        }
        if (response.body() == null) {
            return null;
        }

        Response.Body body = response.body();

        if (byte[].class.equals(type)) {
            return Util.toByteArray(response.body().asInputStream());
        } else if (String.class.equals(type)) {
            return Util.toString(body.asReader());
        } else {
            String result = Util.toString(body.asReader());
            return JSON.parseObject(result, type);
        }
    }
}
